<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <!-- 跨组件通信 -->
      <h2>
        依赖注入 - {{ name }} - <button @click="name = 'wangwu'">btn</button>
      </h2>
      <child></child>
    </div>

    <script src="./vue.js"></script>
    <script>
      const Child2 = {
        data() {
          return {
            name: "tom",
          };
        },
        // inject: ["name"],
        inject: {
          name2: {
            from: "name",
            default: "default value",
          },
          fn: {
            from: "fn",
          },
        },
        template: `
          <div>这是child2子组件 - {{ name2 }} - <button @click="fn(name)">btn</button></div>
        `,
      };

      const Child = {
        components: {
          Child2,
        },
        template: `
          <div>这是child1子组件</div>
          <child2></child2>
        `,
      };

      const app = Vue.createApp({
        data() {
          return {
            name: "lisi",
          };
        },
        methods: {
          fn(n) {
            console.log("fn", n);
            this.name = n;
          },
        },
        components: {
          Child,
        },
        provide() {
          return {
            // name: this.name,
            name: Vue.computed(() => this.name),
            fn: this.fn,
          };
        },
      });

      app.config.unwrapInjectedRef = true;

      app.mount("#app");
    </script>
  </body>
</html>
